package com.sgzn.sgpay.service.impl;

import com.sgzn.sgpay.enums.ReturnResultState;
import com.sgzn.sgpay.enums.SgsResponseCode;
import com.sgzn.sgpay.enums.YesOrNo;
import com.sgzn.sgpay.model.request.*;
import com.sgzn.sgpay.model.response.CurrentPageInfo;
import com.sgzn.sgpay.model.response.DeviceStatisticDto;
import com.sgzn.sgpay.model.response.SgsResultResponse;
import com.sgzn.sgpay.model.response.result.ShopQueryPageResult;
import com.sgzn.sgpay.model.response.vo.ShopDetailVo;
import com.sgzn.sgpay.model.response.vo.ShopVo;
import com.sgzn.sgpay.persistence.dao.TDeviceMapper;
import com.sgzn.sgpay.persistence.dao.TShopMapper;
import com.sgzn.sgpay.persistence.domain.TDeviceExample;
import com.sgzn.sgpay.persistence.domain.TShop;
import com.sgzn.sgpay.persistence.domain.TShopExample;
import com.sgzn.sgpay.persistence.manager.ShopDaoManager;
import com.sgzn.sgpay.service.SgsMchLoginService;
import com.sgzn.sgpay.service.SgsShopService;
import com.sgzn.sgpay.service.converter.ShopReqConverter;
import com.sgzn.sgpay.service.converter.ShopRespConverter;
import com.sgzn.sgpay.service.support.DeviceStatHandler;
import com.sgzn.sgpay.service.support.SgsResponseUtil;
import com.sgzn.sgpay.util.PageCalculator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 门店管理服务接口实现类
 * @author huangsenguang
 * @version Id: SgsShopServiceImpl.java, v 0.1 2018/4/25 21:02 huangsenguang Exp $$
 */
@Service
@Slf4j
public class SgsShopServiceImpl implements SgsShopService {
    @Autowired
    private TShopMapper tShopMapper;
    @Autowired
    private TDeviceMapper tDeviceMapper;
    @Autowired
    private SgsMchLoginService sgsMchLoginService;
    @Autowired
    private ShopDaoManager shopDaoManager;
    @Autowired
    private DeviceStatHandler deviceStatHandler;

    @Override
    @Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public SgsResultResponse<String> addShop(SgsShopAddRequest request) {
        //如果是默认投放地址，则更新其余门店为非默认
        if(YesOrNo.YES.getCode().equals(request.getIsDefaultAddress())){
            updateNotDefault(request.getMchId(),null);
        }
        //新增门店
        TShop tShop = ShopReqConverter.getShopAddRequest(request,request.getMchId());
        int num = tShopMapper.insertSelective(tShop);
        if (num >= 1) {
            return SgsResponseUtil.INSTANCE.success(ReturnResultState.SUCCESS.getCode());
        } else {
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C503.getResponseCode(),SgsResponseCode.C503.getResponseDesc(), ReturnResultState.FAIL.getCode());
        }
    }

    @Override
    @Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public SgsResultResponse<String> updateShop(SgsShopUpdateRequest request) {
        //如果是默认投放地址，则更新其余门店为非默认
        if(YesOrNo.YES.getCode().equals(request.getIsDefaultAddress())){
            updateNotDefault(request.getMchId(),request.getShopId());
        }
        //修改门店
        TShop record = ShopReqConverter.getShopUpdateRequest(request);
        TShopExample example = new TShopExample();
        TShopExample.Criteria criteria = example.createCriteria();
        criteria.andShopIdEqualTo(request.getShopId());
        int num =  tShopMapper.updateByExampleSelective(record, example);
        if (num >= 1) {
            return SgsResponseUtil.INSTANCE.success(ReturnResultState.SUCCESS.getCode());
        } else {
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C503.getResponseCode(),SgsResponseCode.C503.getResponseDesc(), ReturnResultState.FAIL.getCode());
        }
    }

    @Override
    @Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public SgsResultResponse<String> deleteShop(SgsShopDeleteRequest request) {
        //校验是否仍有绑定的设备
        TDeviceExample devExample = new TDeviceExample();
        TDeviceExample.Criteria cra = devExample.createCriteria();
        cra.andMerchantIdEqualTo(request.getMchId()).andShopIdEqualTo(request.getShopId());
        int devNum = tDeviceMapper.countByExample(devExample);
        if(devNum > 0){
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C_SHOP_BIND_DEVICE_EXIST.getResponseCode(),SgsResponseCode.C_SHOP_BIND_DEVICE_EXIST.getResponseDesc());
        }
        TShopExample example = new TShopExample();
        TShopExample.Criteria criteria = example.createCriteria();
        criteria.andShopIdEqualTo(request.getShopId());
        int num = tShopMapper.deleteByExample(example);
        if (num >= 1) {
            return SgsResponseUtil.INSTANCE.success(ReturnResultState.SUCCESS.getCode());
        } else {
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C503.getResponseCode(),SgsResponseCode.C503.getResponseDesc(), ReturnResultState.FAIL.getCode());
        }
    }

    @Override
    public SgsResultResponse<ShopDetailVo> queryShop(SgsShopQueryRequest request) {
        //查询基本信息
        TShop tShop = shopDaoManager.getTShop(request.getShopId());
        //查询该门店下的设备统计数量
        DeviceStatisticDto dto = deviceStatHandler.getDeviceStatisData(request.getMchId(),request.getShopId());
        //组装结果
        ShopDetailVo vo = ShopRespConverter.getShopDetailVo(tShop,dto);
        return SgsResponseUtil.INSTANCE.success(vo);
    }



    @Override
    public SgsResultResponse<ShopQueryPageResult> queryPage(SgsShopQueryPageRequest request) {
        //分页查询
        ShopQueryPageResult result = new ShopQueryPageResult();
        TShopExample example = this.getTShopExampleByPage(request);
        int totalCount = this.tShopMapper.countByExample(example);//获取总数
        CurrentPageInfo pageInfo = PageCalculator.getPageInfo(totalCount, request.getPageQueryParam().getPageSize(),
                request.getPageQueryParam().getCurrentPage());
        StringBuffer clause = new StringBuffer();
        //加上起始和结束行号进行列表查询
        clause.append("updated_at,shop_id desc ");
        clause.append("limit ").append(pageInfo.getStartIndex()).
                append(",").append(pageInfo.getPageSize());
        example.setOrderByClause(clause.toString());
        List<TShop> list = tShopMapper.selectByExample(example);

        result.setShopList(list);
        result.setCurrentPage(pageInfo.getCurrentPage());
        result.setPageSize(pageInfo.getPageSize());
        result.setTotalCount(totalCount);
        result.setTotalPage(pageInfo.getTotalPage());
        return SgsResponseUtil.INSTANCE.success(result);
    }

    @Override
    public SgsResultResponse<List<ShopVo>> queryList(SgsShopQueryListRequest request) {
        TShopExample example = new TShopExample();
        TShopExample.Criteria cra = example.createCriteria();
        cra.andMerchantIdEqualTo(request.getMchId());
        List<TShop> list = tShopMapper.selectByExample(example);
        List<ShopVo> shopVos = assembleShopVoList(list);
        return SgsResponseUtil.INSTANCE.success(shopVos);
    }

    /**
     * 更新商户其余门店为非默认投放地址
     * @param mchId
     * @param shopId
     */
    private void updateNotDefault(String mchId,String shopId){
        TShop record = new TShop();
        record.setIsDefaultAddress(YesOrNo.NO.getCode());
        TShopExample example = new TShopExample();
        TShopExample.Criteria criteria = example.createCriteria();
        criteria.andMerchantIdEqualTo(mchId);
        if(StringUtils.isNotBlank(shopId)){
            criteria.andShopIdNotEqualTo(shopId);
        }
        tShopMapper.updateByExampleSelective(record,example);
    }

    /**
     * 获取查询对象
     * @param request
     * @return
     */
    private TShopExample getTShopExampleByPage(SgsShopQueryPageRequest request){
        TShopExample countExample = new TShopExample();
        TShopExample.Criteria cra = countExample.createCriteria();
        if(StringUtils.isNotBlank(request.getShopId())){
            cra.andShopIdEqualTo(request.getShopId());
        }
        if(StringUtils.isNotBlank(request.getShopName())){
            cra.andShopNameEqualTo(request.getShopName());
        }
        if(StringUtils.isNotBlank(request.getAddress())){
            cra.andAddressEqualTo(request.getAddress());
        }

        if(StringUtils.isNotBlank(request.getShopOwner())){
            cra.andShopOwnerEqualTo(request.getShopOwner());
        }
        if(StringUtils.isNotBlank(request.getContact())){
            cra.andContactEqualTo(request.getContact());
        }
        if(StringUtils.isNotBlank(request.getMchId())){
            cra.andMerchantIdEqualTo(request.getMchId());
        }
        return countExample;
    }

    /**
     * 组装门店id和门店名称信息集合
     * @param list
     */
    private List<ShopVo> assembleShopVoList(List<TShop> list) {
        List<ShopVo> shopList = new ArrayList<>(list.size());
        for (TShop tShop : list) {
            ShopVo shopVo = new ShopVo();
            shopVo.setShopId(tShop.getShopId());
            shopVo.setShopName(tShop.getShopName());
            shopList.add(shopVo);
        }
        return shopList;
    }
}

